<template>
  <div class="video-play-wrap">
    <VideoWrap :message="videoData" @play="handlePlay" @ended="handleEnded" :source="videoData.videoSource"
      height="22rem" />
    <UserMessage :message="videoData" :videoEnded="isVideoEnded" ref="oUserMessage"></UserMessage>
    <VideoMessage :message="videoData" :baseUrl="baseUrl"></VideoMessage>
    <div class="list-box">
      <List :finished="finished" @loadData="getDataList" @reFresh="handleRefresh">
        <ListItem v-for="item of dataList" :key="item" :item="item" @jump="handleVideoJump(item)"></ListItem>
      </List>
    </div>
  </div>
</template>

<script setup>
import { getVideoMessage, updateVideoHistory, videoEndend } from '@/api/videoPlay.js';
import { getHomeVideoList } from '@/api/parentClassroom.js';
import { onMounted, toRefs, ref, reactive, watch, inject } from 'vue';
import { onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router';
import UserMessage from './components/UserMessage/index.vue';
import VideoMessage from './components/VideoMessage/index.vue';

const page = ref({
  currentPage: 1,
  pageSize: 20,
  sort: "desc",
  sidx: "playCount"
});


const column = ref(2);
const dataList = ref([]);
const finished = ref(false);


//  下拉刷新
const handleRefresh = () => {
  page.value.currentPage = 1;
  finished.value = false;
  dataList.value = []
  debounce(getDataList, 800)();
}


//  防抖
function debounce(func, delay) {
  let timeout
  return function () {
    const _this = this
    const args = [...arguments]
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      func.apply(_this, args)
    }, delay)
  }
}

//  视频源
const source = ref('');

const route = useRoute();
const router = useRouter();

const baseUrl = ref('/VideoPlay/' + route.params.videoId);

onMounted(async () => {
  const toast = inject('loading');
  toast.showLoading();
  await Promise.all([
    setVideoData(),
    getDataList()
  ])
  toast.hideLoading();
})

//  视频播放
const handlePlay = () => {
  const { videoId } = videoData.value;
  const parentId = JSON.parse(localStorage.getItem('parentId'));
  //  设置播放记录
  updateVideoHistory({ videoId, parentId });
}

const isVideoEnded = ref(false);
const oUserMessage = ref(null);


//  视频播放完成
const handleEnded = async () => {
  isVideoEnded.value = true;
  let t = null;
  t = setTimeout(() => {
    oUserMessage.value.handleAnswer();
    clearTimeout(t);
  });
}

// 切换路由参数，实现播放
const handleVideoJump = (data) => {
  //  获取 videoId 跳转到详情页
  const { videoId = '' } = data;
  router.push({ path: `/VideoPlay/${videoId}` });
}

//  监听路由调整
watch(() => route.params, () => {
  location.reload();
})

//  请求数据
async function getDataList() {
  if (finished.value) return;
  const { code, data } = await getHomeVideoList(page.value);

  if (code == 200) {
    const { currentPage, pageSize, total } = data.pagination;
    //  判断是否是第一页
    if (currentPage === 1) {
      dataList.value = [];
    }

    // 判断是否到底
    if (currentPage * pageSize >= total) {
      finished.value = true;
    }

    //  格式化数据
    dataList.value = dataList.value.concat(setDataList(data.list));
    //  准备加载新的数据
    page.value.currentPage++;
  }
}

//  处理数据格式
function setDataList(data) {
  const _data = [...data].map(item => {
    //  处理图片
    try {
      item.videoPic = JSON.parse(item.videoPic);
      item.image = item.videoPic[0].url ? process.env.VITE_API_API_IMAGE_URL + item.videoPic[0].url : '';
    } catch (ev) {
      item.image = '';
    }

    return item;
  });

  return _data;
}

const videoData = ref({});
//  获取页面详细信息
async function setVideoData() {
  const id = route.params.videoId || '';
  const { code, data } = await getVideoMessage(id);
  if (code === 200) {
    try {
      data.videoFile = JSON.parse(data.videoFile);
      data.fileId = data.videoFile[0].fileId;
      data.videoSource = process.env.VUE_APP_API_BASE_URL + '/spgl/SpdbVideo/getVideo?fileId=' + (data.fileId || '');
      // data.videoSource = 'api/spgl/SpdbVideo/getVideo?fileId=20240425_553135991724974021.mp4'
    } catch (ev) {
      data.videoSource = '';
    }

    //  处理图片
    try {
      data.videoPic = JSON.parse(data.videoPic);
      data.image = data.videoPic[0].url ? process.env.VITE_API_API_IMAGE_URL + data.videoPic[0].url : '';
    } catch (ev) {
      data.image = '';
    }

    try { data.videoLabelList = JSON.parse(data.videoLabelList) } catch (ev) { data.videoLabelList = [] }

    videoData.value = data;
  }
}
</script>

<style lang="scss" scoped>
.list-box {
  flex: 1;
  padding: 0 1rem;
  box-sizing: border-box;
}
</style>
